//
//  FifthVideoViewController.m
//  Project_B
//
//  Created by 张闯的mac pro on 15/11/28.
//  Copyright © 2015年 张闯. All rights reserved.
//

#import "FifthVideoViewController.h"
#import "AFNetworkHandler.h"
#import "FifthVideoModel.h"
#import "MJRefresh.h"
#import "FifthVideoTableViewCell.h"
#import "FifthVideoDetailViewController.h"
#import "ShareTableView.h"
#import "FifthMusicTableViewCell.h"
#import "MBProgressHUD.h"
#import "RESideMenu.h"
#import "RCNetWorking.h"
#import "MusicViewController.h"
#import "CoreDataManager.h"
#import "UIImage+GIF.h"

@interface FifthVideoViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UITableView *MusicView;
@property (nonatomic, strong) NSMutableArray *MusicdataArr;
@property (nonatomic, strong) UIView * rightview;
@property (nonatomic, strong) CoreDataManager *coreDataManager;
@property (nonatomic, assign) NSInteger i;
@property (nonatomic, assign) NSInteger p;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, strong) MBProgressHUD *hud1;
@property (nonatomic, assign) BOOL jude;
@property (nonatomic, strong) UIButton *button;
@end

@implementation FifthVideoViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"加载" object:nil];
}


- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
      self.p = 1;
    
    self.dataArr = [NSMutableArray array];
    self.i = 10;
    self.navigationItem.title = @"精选视频";
    
    //注册通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(footData) name:@"加载" object:nil];
    
    [self getVideoData];
    [self createVideoTableView];
    [self createClickToTop];
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:NO];
    self.hud.animationType = MBProgressHUDAnimationFade;
    [self mjMethod];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-category"] style:UIBarButtonItemStylePlain target:self action:@selector(presentLeftMenuViewController:)];
    [self.navigationItem.leftBarButtonItem setTintColor:[UIColor whiteColor]];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Music"] style:UIBarButtonItemStylePlain target:self action:@selector(AVction)];
    self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
    
    self.jude = YES;
    
}

- (void)createClickToTop
{
    self.button = [UIButton buttonWithType:UIButtonTypeSystem];
    self.button.frame = CGRectMake(330, 500, 30, 30);
    [self.button setBackgroundImage:[UIImage imageNamed:@"top"] forState:0];
    self.button.backgroundColor = [UIColor colorWithRed:60.0 / 255 green:149.0 / 255 blue:58.0 / 255 alpha:1];
    self.button.layer.cornerRadius = 5;
    [self.button addTarget:self action:@selector(topAction) forControlEvents:UIControlEventTouchUpInside];
}

- (void)topAction
{
    [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    [self.MusicView setContentOffset:CGPointMake(0, 0) animated:YES];
}



- (void)footData
{
    NSString *str = [NSString stringWithFormat:@"http://baobab.wandoujia.com/api/v1/videos?start=%ld&num=10&categoryName=旅行&strategy=shareCount", self.i += 10];
    
    [AFNetworkHandler getUrl:str cookie:nil result:^(id result) {
        
        NSArray *arr = result[@"videoList"];
        [self.dataArr addObjectsFromArray:[FifthVideoModel transformWithArray:arr]];
        [self.tableView reloadData];
        [self.tableView.mj_footer endRefreshing];
        
    }];
}

- (void)footMusicData
{
    self.p ++;
    NSString *sti = [NSString stringWithFormat:@"http://mobile.ximalaya.com/mobile/discovery/v1/category/album?calcDimension=hot&categoryId=2&device=iPhone&pageId=%ld&pageSize=20&status=0&tagName=%%7C%%E7%%BA%%AF%%E9%%9F%%B3%%E4%%B9%%90%%7C", self.i];
    
    [RCNetWorking GETDataWithAFN:sti cookie:nil completion:^(id result) {
        NSArray *arr = result[@"list"];
        [self.MusicdataArr addObjectsFromArray: [FifthVideoModel transformWithArray:arr]];
        [self.MusicView reloadData];
        [self.MusicView.mj_footer endRefreshing];
    } error:^(id error) {
        
    }];
}

- (void)getVideoData
{
    [AFNetworkHandler getUrl:@"http://baobab.wandoujia.com/api/v1/videos?start=0&num=10&categoryName=旅行&strategy=shareCount" cookie:nil result:^(id result) {
        NSArray *arr = result[@"videoList"];
        self.dataArr = [FifthVideoModel transformWithArray:arr];
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        [self.hud removeFromSuperview];
        [self.view addSubview:self.tableView];
    }];
    
#pragma mark - 音乐
    NSString * sti = @"http://mobile.ximalaya.com/mobile/discovery/v1/category/album?calcDimension=hot&categoryId=2&device=iPhone&pageId=1&pageSize=20&status=0&tagName=%E7%B2%BE%E9%80%89%7C%E6%AD%8C%E5%8D%95";

    [RCNetWorking GETDataWithAFN:sti cookie:nil completion:^(id result) {
        self.MusicdataArr = [NSMutableArray array];
        NSArray *arr = result[@"list"];
        self.MusicdataArr = [FifthVideoModel transformWithArray:arr];
        [self.MusicView reloadData];
        [self.hud1 removeFromSuperview];
        [self.MusicView.mj_header endRefreshing];
    } error:^(id error) {
        
    }];
}

#pragma mark - 音乐播放
- (void)AVction
{
    if (self.jude == YES) {
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-icon@3x"] style:UIBarButtonItemStylePlain target:self action:@selector(AVction)];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        [UIView animateWithDuration:0.3 animations:^{
            
            self.MusicView.frame = CGRectMake(0, 0, 375, 667 - 64);
            self.tableView.frame = CGRectMake(-375, 0, 375, 667 - 64);
            self.navigationItem.title = @"精选音乐";
            
        }];
        
        self.jude = NO;
        
    } else {
        
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"Music"] style:UIBarButtonItemStylePlain target:self action:@selector(AVction)];
        self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
        [UIView animateWithDuration:0.3 animations:^{
            self.MusicView.frame = CGRectMake(375, 0, 375, 667 - 64);
            self.tableView.frame = CGRectMake(0, 0, 375, 667 - 64);
            self.navigationItem.title = @"精选视频";
        }];
        self.jude = YES;
    }
}

- (void)createVideoTableView
{
    self.tableView = [ShareTableView shareInstance];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[FifthVideoTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    self.MusicView = [[UITableView alloc] initWithFrame:CGRectMake(375, 0, 375, 667 - 64) style:UITableViewStylePlain];
    self.MusicView.delegate = self;
    self.MusicView.dataSource = self;
    [self.MusicView registerClass:[FifthMusicTableViewCell class] forCellReuseIdentifier:@"Music"];
    [self.view addSubview:self.MusicView];
    self.hud1 = [MBProgressHUD showHUDAddedTo:self.view animated:NO];
    self.hud1.animationType = MBProgressHUDAnimationFade;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return self.dataArr.count;
    } else {
        return self.MusicdataArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        FifthVideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
        cell.fifModel = self.dataArr[indexPath.row];
        return cell;
    } else {
        FifthMusicTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Music"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        cell.model = self.MusicdataArr[indexPath.row];
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    if (tableView == self.tableView) {
        FifthVideoDetailViewController *detailVC = [[FifthVideoDetailViewController alloc] init];
        
        detailVC.detailModel = self.dataArr[indexPath.row];
        detailVC.indexPath = indexPath;
        detailVC.modelArr = self.dataArr;
        detailVC.i = indexPath.row;
        
        [detailVC setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
        [self presentViewController:detailVC animated:YES completion:^{
            nil;
        }];
        
        self.jude = YES;
        
    } else {
        MusicViewController * main = [[MusicViewController alloc] init];
        main.albumId = [self.MusicdataArr[indexPath.row] albumId];
        main.name = [self.MusicdataArr[indexPath.row] title];
        main.image = [self.MusicdataArr[indexPath.row] coverMiddle];
        main.intro = [self.MusicdataArr[indexPath.row] intro];
        [self.navigationController pushViewController:main animated:YES];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        return 200;
    } else {
        return 100;
    }
}

- (void)mjMethod
{
    MJRefreshGifHeader *head = [[MJRefreshGifHeader alloc] init];
    __weak typeof(self) weakSelf = self;
    head = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf getVideoData];
        } else {
            return;
        }
    }];
    NSString *name = @"gif1.gif";
    NSString *filePath = [[NSBundle bundleWithPath:[[NSBundle mainBundle] bundlePath]] pathForResource:name ofType:nil];
    NSData *imageData = [NSData dataWithContentsOfFile:filePath];
    UIImage *image = [UIImage sd_animatedGIFWithData:imageData];
    [head setImages:@[image] duration:2 forState:2];
    self.tableView.mj_header = head;
    MJRefreshAutoNormalFooter *foot = [[MJRefreshAutoNormalFooter alloc] init];
    foot = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf footData];
        } else {
            return;
        }
    }];
    self.tableView.mj_footer = foot;
    
    self.MusicView.mj_footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        __strong typeof(self) strongSelf = weakSelf;
        if (strongSelf) {
            [strongSelf footMusicData];
        } else {
            return;
        }
    }];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView == self.tableView || scrollView == self.MusicView) {
        if (self.tableView.contentOffset.y > 1000 || self.MusicView.contentOffset.y > 1000) {
            [self.view addSubview:self.button];
        } else {
            [self.button removeFromSuperview];
        }
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
